package com.itheima.appserver.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;


import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.config.MyThreadLocal;
import com.itheima.appserver.excepiton.ErrInfo;
import com.itheima.appserver.excepiton.ErroResult;
import com.itheima.appserver.excepiton.MyEx;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.User;
import com.itheima.commons.utils.SendMsgUtil;
import com.itheima.dubbo.interfaces.UserApi;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference
    private UserApi userApi;

    //发送验证码
    public void loginSendMsg(String phone) {
        if (!Validator.isMobile(phone)){
            //不是手机号抛对应异常
            throw  new MyEx();
        }
        String code = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        if (!StrUtil.isEmpty(code)) {
            //验证码在redis还存在，则提示验证码未失效
            throw new MyEx(ErroResult.fail(ErrInfo.codeTimeError));
        }
        //发送验证码
        String num = RandomUtil.randomNumbers(6);
        System.out.println("num = " + num);

        //Boolean result = SendMsgUtil.sendMsg(phone, Constants.SMS_CODE_TEMPLATE, num);
        //if (!result) {
        //    //提示：已发送验证码，请稍后再试
        //    throw new MyEx(ErroResult.fail(ErrInfo.codeTimeInError));
        //}

        redisTemplate.opsForValue().set(Constants.SMS_CODE + phone,num,5, TimeUnit.MINUTES);
    }
    //校验验证码
    public Map<String, Object> verificationCode(String phone, String code) {
        if (!Validator.isMobile(phone)){
            //不是手机号抛对应异常
            throw  new MyEx(ErroResult.fail(ErrInfo.phoneError));
        }

        String num = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        //如果redis中没有该手机号验证码，则提示验证码已超时
        if (num == null ){
            throw new MyEx(ErroResult.fail(ErrInfo.codeTimeOutError));
        }
        //传入验证码为空或与redis中不匹配，验证码错误
        if ( code == null || !num.equals(code)){
            throw new MyEx(ErroResult.fail(ErrInfo.codeError));
        }

        //判断是否为新用户
        User user = userApi.findByPhone(phone);
        HashMap<String, Object> map = new HashMap<>();
        map.put("isNew",false);
        if (ObjectUtil.isNull(user)){
            //则为新用户
            user = userApi.addUser(User.builder()
                    .mobile(phone)
                    .password(SecureUtil.md5(Constants.INIT_PASSWORD))  //初始化密码12356，用md5加密
                    .created(new Date())
                    .updated(new Date())
                    .build());
            map.put("isNew",true);
            System.out.println(user);
        }

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("uid", user.getId());
        hashMap.put("phoneNum", user.getMobile());
        hashMap.put(JWTPayload.EXPIRES_AT, DateTime.of(System.currentTimeMillis() + Constants.JWT_TIME_OUT));

        String token = JWTUtil.createToken(hashMap, Constants.JWT_SECRET.getBytes());

        //如果为老用户
        map.put("token",token);
        System.out.println(token);
        //无任何异常则删除redis中该手机号对应的code
        redisTemplate.delete(Constants.SMS_CODE + phone);
        return map;

    }



}
